package com.woniuxy.wd.dao.util;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Interceptor implements InvocationHandler{
	
//	private DAOTemplet dt;
	private Object obj;
	private DAOAdapter dao;
	
	public Interceptor(Object obj){
		this.obj = obj;
		String objectName = obj.toString();
		int start = objectName.lastIndexOf(".") + 1;
		int end = objectName.indexOf("DAO@");
		String tableName = objectName.substring(start,end).toLowerCase();
		dao = (DAOAdapter)this.obj;
		Connection con = DBUtil.getConnection();
		dao.initTemplet(con);
		dao.getTemplet().setTableName(tableName);
	}

	@Override
	public Object invoke(Object obj, Method method, Object[] arg2)
			throws Throwable {
		String methodName = method.getName();
		

		if(methodName.startsWith("update") || methodName.startsWith("delete") || methodName.startsWith("save")){
			try{
				Object o = method.invoke(this.obj,arg2);
				
				dao.getTemplet().getCon().commit();
				return o;
			} catch(Exception e){
				dao.getTemplet().getCon().rollback();
				return null;
			} finally{
				dao.getTemplet().getCon().close();
			}
		}else{
			try{
				return method.invoke(this.obj,arg2);
			}catch(Exception e){
				
			}finally{
				dao.getTemplet().getCon().close();
			}
			
			return null;
		}
	}

}
